﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using Kingdee.BOS.WebApi.Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WSDZ.KM.ZH.XiaoManIntegrating40
{
    /// <summary>
    /// 小满
    /// </summary>
    [Description("Erp获取小满客户"), HotUpdate]
    public class XiaoManCustomerManager
    {
        public string btype = "Erp获取小满客户";
        /// <summary>
        /// 日志文件路径
        /// </summary>
        public string logType = "Erp获取小满客户";
        public string formId = "BD_Customer";
        public TokenData TokenObj = null;

        public string XMUrl1 = "https://api-sandbox.xiaoman.cn/v1/company/updates";
        public string XMUrl2 = "https://api-sandbox.xiaoman.cn/v1/company/info";

        public Context ctx;
        public string date1;
        public string date2;
        public string xiaomanId;
        public int PageSize = 1000;
        public int AllPage = 1;

        Dictionary<string, string> headers;

        public void Main(Context c, string d1, string d2, string xmid = "")
        {
            try
            {
                ctx = c;
                date1 = d1;
                date2 = d2;
                xiaomanId = xmid;
                logType = $@"{logType}\{DateTime.Now.ToString("yyyy_MM_dd_HH")}";
                var tokens = PostHelper.GetToken(logType);
                if (!tokens.Item1)
                {
                    LogHelper.XiaoManLog($"【获取token错误】【msg:{tokens.Item2.msg}】", logType);
                    return;
                }
                TokenObj = tokens.Item2;
                DealMethod();
            }
            catch (Exception ex)
            {
                LogHelper.XiaoManLog($"【异常A1001】【msg:{ex.Message}】", logType);
            }

        }

        public void DealMethod()
        {

            headers = new Dictionary<string, string>();
            headers.Add("Authorization", $@"Bearer {TokenObj.token}");
            List<CustUpdateData> CUList = new List<CustUpdateData>();

            for (int i = 1; i <= AllPage; i++)
            {
                try
                {
                    Dictionary<string, string> paraDics = new Dictionary<string, string>();
                    //long D1 = date1.ToDateTime().GetTimeStampV1();
                    //long D2= date2.ToDateTime().GetTimeStampV1();
                    //paraDics.Add("start_time", D1.ToStringV1());
                    //paraDics.Add("end_time", D2.ToStringV1());
                    paraDics.Add("start_time", date1);
                    paraDics.Add("end_time", date2);
                    paraDics.Add("start_index", i.ToStringV1());
                    paraDics.Add("count", PageSize.ToStringV1());
                    string dataContent = PostHelper.DicToParameter(paraDics);
                    string url = XMUrl1 + $@"?{dataContent}";
                    string resultStr = PostHelper.Get(url,"", headers);
                    //string resultStr = PostHelper.Get(XMUrl1, dataContent, headers);
                    LogHelper.XiaoManLog($"【获取小满客户列表】\nurl:【{url}】\nheaders:{JsonConvert.SerializeObject(headers)}\n传入{dataContent}\n返回:{resultStr}", logType);
                    JObject reObj = JsonConvert.DeserializeObject<JObject>(resultStr);
                    if (reObj["code"].ToStringV1().EqualsV1("200") && reObj["message"].ToStringV1().EqualsV1("success"))
                    {

                        JObject dataObj = JsonConvert.DeserializeObject<JObject>(reObj["data"].ToStringV1());

                        int totalItem = dataObj["totalItem"].ToStringV1().ToInt32V1();
                        AllPage = totalItem <= PageSize ? 1 : totalItem % PageSize > 0 ? totalItem / PageSize + 1 : totalItem / PageSize;

                        JArray dataArray = JsonConvert.DeserializeObject<JArray>(dataObj["list"].ToStringV1());
                        if (dataArray != null && dataArray.Count > 0)
                        {
                            List<CustUpdateData> clist = dataArray.Select(x => new CustUpdateData
                            {

                                Id = x["company_id"].ToStringV1(),
                                Name = x["name"].ToStringV1(),
                                ShortName = x["short_name"].ToStringV1(),
                                SerId = x["serial_id"].ToStringV1(),
                                ModifyDate = x["order_time"].ToStringV1().ToDateTime(),
                                CreateDate = x["create_time"].ToStringV1(),
                            }).ToList();
                            CUList.AddRange(clist);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.XiaoManLog($"【获取小满客户列表】【异常C2001】\n【msg:{ex.Message}】", logType);
                    continue;
                }

            }

            CUList = CUList.Where(x => !x.ShortName.IsNullOrEmptyOrWhiteSpace()).ToList();
            if (!xiaomanId.IsNullOrEmptyOrWhiteSpace())
                CUList = CUList.Where(x => x.Id.EqualsV1(xiaomanId)).ToList();
            if (CUList.Count > 0)
            {
                CUList = CUList.GroupBy(x => x.Id).Select(x => x.FirstOrDefault()).ToList();
                DealMethodV1(CUList);
            }

        }
        /// <summary>
        /// 客户
        /// </summary>
        //List<Cust> custList = new List<Cust>();
        /// <summary>
        /// 销售员
        /// </summary>
        List<Saler> salerList = new List<Saler>();
        /// <summary>
        /// 辅助资料
        /// </summary>
        List<AuxiliaryInfo> auxiliaryList = new List<AuxiliaryInfo>();
        List<AuxiliaryInfo> MJList = new List<AuxiliaryInfo>();
        /// <summary>
        /// 客户分组
        /// </summary>
        List<AuxiliaryInfo> custGroupList = new List<AuxiliaryInfo>();
        /// <summary>
        /// 客户来源
        /// </summary>
        List<AuxiliaryInfo> custSourceList = new List<AuxiliaryInfo>();
        /// <summary>
        /// 客户等级
        /// </summary>
        List<AuxiliaryInfo> custGradeList = new List<AuxiliaryInfo>();
        /// <summary>
        /// 币别
        /// </summary>
        List<AuxiliaryInfo> currencyList = new List<AuxiliaryInfo>();
        /// <summary>
        /// 收款条件
        /// </summary>
        List<AuxiliaryInfo> receiptConditionList = new List<AuxiliaryInfo>();
        /// <summary>
        /// 结算方式
        /// </summary>
        List<AuxiliaryInfo> settleTypeList = new List<AuxiliaryInfo>();
        /// <summary>
        /// 价格条款
        /// </summary>
        List<AuxiliaryInfo> priceClauseList = new List<AuxiliaryInfo>();
        /// <summary>
        /// 税率
        /// </summary>
        List<AuxiliaryInfo> taxRateList = new List<AuxiliaryInfo>();

        public void DealMethodV1(List<CustUpdateData> CUList)
        {
            string loginMsg = string.Empty;
            if (!K3HelperV1.Login(ctx, ref loginMsg))
                if (!K3HelperV1.Login(ctx, ref loginMsg))
                {
                    LogHelper.XiaoManLog($"【A1001】【登录失败】\n【msg:{loginMsg}】", logType);
                    return;
                }

            //查询erp客户信息
            {
//                string sql = $@"/*dialect*/ select 
//Id=cust.FCUSTID
//,Number=cust.FNUMBER
//,xmId=cust.F_RLKX_xmcustid1
//,salerName=salerL.FNAME
//from T_BD_CUSTOMER cust
//left join V_BD_SALESMAN saler on cust.FSELLER=saler.fid
//left join V_BD_SALESMAN_L salerL on saler.fid=salerL.fid and salerL.FLOCALEID=2052";
//                DynamicObjectCollection cdatas = DBUtils.ExecuteDynamicObject(ctx, sql);
//                if (cdatas != null && cdatas.Count > 0)
//                    custList = cdatas.DynamicObjectCollectionToDataList<Cust>();
            }
            //客户分组
            {
                string sql = $@"select 
Id=main.FID
,Number=FNUMBER
,Name=mainL.FNAME
from T_BD_CUSTOMERGROUP main
left join T_BD_CUSTOMERGROUP_L mainL on main.FID=mainL.FID and mainL.FLOCALEID=2052";
                DynamicObjectCollection cdatas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (cdatas != null && cdatas.Count > 0)
                    custGroupList = cdatas.DynamicObjectCollectionToDataList<AuxiliaryInfo>();
            }
            //客户来源
            {
                string sql = $@"select 
Id=main.FID
,Number=FNUMBER
,Name=mainL.FNAME
from T_BAS_PREBDONE main
left join T_BAS_PREBDONE_L mainL on main.FID=mainL.FID and mainL.FLOCALEID=2052
where main.FDOCUMENTSTATUS='C'";
                DynamicObjectCollection cdatas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (cdatas != null && cdatas.Count > 0)
                    custSourceList = cdatas.DynamicObjectCollectionToDataList<AuxiliaryInfo>();
            }
            //客户等级
            {
                string sql = $@"select 
Id=main.FID
,Number=FNUMBER
,Name=mainL.FNAME
from T_BAS_PREBDFIVE main
left join T_BAS_PREBDFIVE_L mainL on main.FID=mainL.FID and mainL.FLOCALEID=2052
where main.FDOCUMENTSTATUS='C'";
                DynamicObjectCollection cdatas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (cdatas != null && cdatas.Count > 0)
                    custGradeList = cdatas.DynamicObjectCollectionToDataList<AuxiliaryInfo>();
            }
            //币别
            {
                string sql = $@"select 
Id=main.FCURRENCYID
,Number=FNUMBER
,Name=mainL.FNAME
from T_BD_CURRENCY main
left join T_BD_CURRENCY_L mainL on main.FCURRENCYID=mainL.FCURRENCYID and mainL.FLOCALEID=2052
where main.FDOCUMENTSTATUS='C'";
                DynamicObjectCollection cdatas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (cdatas != null && cdatas.Count > 0)
                    currencyList = cdatas.DynamicObjectCollectionToDataList<AuxiliaryInfo>();
            }
            //收款条件
            {
                string sql = $@"select 
Id=main.FID
,Number=FNUMBER
,Name=mainL.FNAME
from T_BD_RecCondition main
left join T_BD_RecCondition_L mainL on main.FID=mainL.FID and mainL.FLOCALEID=2052
where main.FDOCUMENTSTATUS='C'";
                DynamicObjectCollection cdatas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (cdatas != null && cdatas.Count > 0)
                    receiptConditionList = cdatas.DynamicObjectCollectionToDataList<AuxiliaryInfo>();
            }
            //结算方式
            {
                string sql = $@"select 
Id=main.FID
,Number=FNUMBER
,Name=mainL.FNAME
from T_BD_SETTLETYPE main
left join T_BD_SETTLETYPE_L mainL on main.FID=mainL.FID and mainL.FLOCALEID=2052
where main.FDOCUMENTSTATUS='C'";
                DynamicObjectCollection cdatas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (cdatas != null && cdatas.Count > 0)
                    settleTypeList = cdatas.DynamicObjectCollectionToDataList<AuxiliaryInfo>();
            }
            //价格条款
            {
                string sql = $@"select 
Id=main.FID
,Number=FNUMBER
,Name=mainL.FDESCRIPTION
from T_BAS_PREBDFOUR main
left join T_BAS_PREBDFOUR_L mainL on main.FID=mainL.FID and mainL.FLOCALEID=2052
where main.FDOCUMENTSTATUS='C'";
                DynamicObjectCollection cdatas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (cdatas != null && cdatas.Count > 0)
                    priceClauseList = cdatas.DynamicObjectCollectionToDataList<AuxiliaryInfo>();
            }
            //税率
            {
                string sql = $@"select 
Id=main.FID
,Number=FNUMBER
,Name=mainL.FNAME
from T_BD_TAXRATE main
left join T_BD_TAXRATE_L mainL on main.FID=mainL.FID and mainL.FLOCALEID=2052
where main.FDOCUMENTSTATUS='C'";
                DynamicObjectCollection cdatas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (cdatas != null && cdatas.Count > 0)
                    taxRateList = cdatas.DynamicObjectCollectionToDataList<AuxiliaryInfo>();
            }

            //销售员信息
            {
                string sql = $@"/*dialect*/ select 
Id=saler.fid
,Number=saler.FNUMBER
,Name=salerL.FNAME
,dptNumebr=dpt.FNUMBER
from V_BD_SALESMAN saler
left join V_BD_SALESMAN_L salerL on saler.fid=salerL.fid and salerL.FLOCALEID=2052
left join T_BD_DEPARTMENT dpt on saler.FDEPTID=dpt.FDEPTID
where saler.FDOCUMENTSTATUS='C'";
                DynamicObjectCollection cdatas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (cdatas != null && cdatas.Count > 0)
                    salerList = cdatas.DynamicObjectCollectionToDataList<Saler>();
            }
            //查询辅助资料
            {
                string sql = $@"select 
TypeNumber=lb.FNUMBER
,TypeName=lbL.FNAME
,Number= enty.FNUMBER
,Name= entyL.FDATAVALUE
from T_BAS_ASSISTANTDATAENTRY enty
left join T_BAS_ASSISTANTDATAENTRY_L entyL on enty.FENTRYID=entyL.FENTRYID and entyL.FLOCALEID=2052
left join T_BAS_ASSISTANTDATA lb on enty.FID=lb.FID
left join T_BAS_ASSISTANTDATA_L lbL on lb.FID=lbL.FID and lbL.FLOCALEID=2052";
                DynamicObjectCollection cdatas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (cdatas != null && cdatas.Count > 0)
                    auxiliaryList = cdatas.DynamicObjectCollectionToDataList<AuxiliaryInfo>();
            }
            //枚举值
            {
                string sql = $@"select 
TypeNumber=mjType.FID
,TypeName=mjTypeL.FNAME  --枚举类型名称
,Number= mj.FVALUE  --枚举值
,Name= mjL.FCAPTION  --枚举值名称
from T_META_FORMENUM mjType
inner join T_META_FORMENUM_L mjTypeL on mjType.FID =mjTypeL.FID and mjTypeL.FLOCALEID = 2052 
inner join T_META_FORMENUMITEM mj on mj.FID = mjType.FID
inner join T_META_FORMENUMITEM_L mjL ON mj.FENUMID = mjL.FENUMID and mjL.FLOCALEID = 2052
where mj.FINVALID=0";
                DynamicObjectCollection cdatas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (cdatas != null && cdatas.Count > 0)
                    MJList = cdatas.DynamicObjectCollectionToDataList<AuxiliaryInfo>();
            }


            List<XMFieldData> xmdatas = new List<XMFieldData>();
            foreach (CustUpdateData uObj in CUList)
            {
                try
                {

                    xmdatas = new List<XMFieldData>();

                    //{
                    //    string ttttt = File.ReadAllText($@"D:\TData\32849.txt");
                    //    JObject reObjA = JsonConvert.DeserializeObject<JObject>(ttttt);
                    //    JObject dataObjA = JsonConvert.DeserializeObject<JObject>(reObjA["data"].ToStringV1());
                    //    string json = FillContent(dataObjA, uObj);
                    //    return;
                    //}
                    //if (uObj.SerId.EqualsV1("32036"))
                    //{
                    //    int aaaa = 1;
                    //}
                    //else
                    //{
                    //    return;
                    //}



                    //查询客户详细信息
                    Dictionary<string, string> paraDics = new Dictionary<string, string>();
                    paraDics.Add("company_id", uObj.Id);
                    string dataContent = PostHelper.DicToParameter(paraDics);
                    //string resultStr = PostHelper.Get(XMUrl2, dataContent, headers);
                    string xmUrl = XMUrl2 + "?" + dataContent;
                    string resultStr = PostHelper.Get(xmUrl, "", headers);
                    LogHelper.XiaoManLog($"【客户详细信息】\nheaders:{JsonConvert.SerializeObject(headers)}\n返回:{resultStr}", logType);
                    JObject reObj = JsonConvert.DeserializeObject<JObject>(resultStr);
                    if (reObj["code"].ToStringV1().EqualsV1("200") && reObj["message"].ToStringV1().EqualsV1("success"))
                    {
                        JObject dataObj = JsonConvert.DeserializeObject<JObject>(reObj["data"].ToStringV1());


                        //测试专用
                        //{
                        //    if (uObj.SerId.EqualsV1("32036"))
                        //    {
                        //        string json = FillContent(dataObj, uObj);
                        //        continue;
                        //    }
                        //    else
                        //    {
                        //        continue;
                        //    }

                        //}


                        Cust erpCustObj = null;
                        //var erpCustObj = custList.Where(x => x.Number.EqualsV1(uObj.SerId)).FirstOrDefault();
                        string sql = $@"select top 1
custId=cust.FCUSTID
,Number=FNUMBER
,name=custL.FNAME
,shortName=custL.FSHORTNAME
from T_BD_CUSTOMER cust
left join T_BD_CUSTOMER_L custL on cust.FCUSTID=custL.FCUSTID and custL.FLOCALEID=2052
--where FNUMBER='{uObj.SerId}'
where ISNULL(custL.FSHORTNAME,'')='{uObj.ShortName}'
";
                        DynamicObjectCollection datas = DBUtils.ExecuteDynamicObject(ctx,sql);
                        if (datas!=null&&datas.Count>0)
                        {
                            erpCustObj = new Cust();
                            DynamicObject cobj = datas[0];
                            erpCustObj.Id = cobj["custId"].ToStringV1().ToInt32V1();
                            erpCustObj.Number = uObj.SerId;
                        }

                        //erp已存在 则更新销售员即可  若不存在 则在erp新增一个 客户
                        JArray companyArray = JsonConvert.DeserializeObject<JArray>(dataObj["company"].ToStringV1());
                        if (companyArray == null || companyArray.Count < 1)
                            continue;
                        foreach (JObject item in companyArray)
                        {
                            JArray fieldArray = JsonConvert.DeserializeObject<JArray>(item["fields"].ToStringV1());
                            if (fieldArray == null || fieldArray.Count < 1)
                                continue;
                            foreach (JObject fielddata in fieldArray)
                            {
                                XMFieldData xmd = new XMFieldData();
                                xmd.group_id = item["group_id"].ToStringV1();
                                xmd.group_name = item["group_name"].ToStringV1();
                                xmd.id = fielddata["id"].ToStringV1();
                                xmd.name = fielddata["name"].ToStringV1();
                                xmd.field_type = fielddata["field_type"].ToStringV1();
                                xmd.value = fielddata["value"].ToStringV1();
                                xmdatas.Add(xmd);
                            }
                        }

                        //获取成交状态
                        //string cjzt = "34856303195581".GetValueByKey(xmdatas);
                        //string cjzt = "34856303195581".GetValueByKey(xmdatas);
                        //是否同步金蝶
                        bool isUpdateToK3 = "38669239529883".GetValueByKey(xmdatas) =="是";
                        if (!isUpdateToK3)
                        {
                            LogHelper.XiaoManLog($"客户【{uObj.Id}】{uObj.Name}不同步金蝶,跳过", logType);
                            continue;
                        }
                        if (erpCustObj != null)
                        {
                            //获取业务员
                            //string ywy = "28514799207966".GetValueByKey(xmdatas);
                            //int salerId = salerList.Where(x => x.Name.EqualsV1(ywy)).Select(x => x.Id).FirstOrDefault();
                            //string sql_u = $@"update T_BD_CUSTOMER set FSELLER={salerId},F_RLKX_xmcustid1='{uObj.Id}' where FCUSTID={erpCustObj.Id}";
                            //DBUtils.Execute(ctx, sql_u);

                            string sql_u = $@"update T_BD_CUSTOMER set F_RLKX_xmcustid1='{uObj.Id}' where FCUSTID={erpCustObj.Id}";
                            DBUtils.Execute(ctx, sql_u);
                        }
                        //新增客户
                        else
                        {
                            string json = FillContent(dataObj, uObj, xmdatas);
                            string msg = string.Empty;
                            JObject returnData = new JObject();
                            bool isok = K3HelperV1.SaveV1(ctx, formId, json, ref msg, ref returnData);
                            if (!isok)
                                isok = K3HelperV1.DraftV1(ctx, formId, json, ref msg, ref returnData);
                            if (isok)
                            {
                                LogHelper.XiaoManLog($"【客户保存成功】【{uObj.Name}】\n【json:{json}】", logType);
                                var suStr = returnData["Result"]["ResponseStatus"]["SuccessEntitys"].ToStringV1();
                                JArray array = JsonConvert.DeserializeObject<JArray>(suStr);
                                int custId = array.Select(x => x["Id"].ToStringV1().ToInt32V1()).FirstOrDefault();
                                string custNo = array.Select(x => x["Number"].ToStringV1()).FirstOrDefault();
                                //创建联系人
                                {
                                    //string lxrStr = "customers".GetValueByKey(xmdatas);
                                    string lxrStr = dataObj["customers"].ToStringV1();
                                    JArray lxrArray = JsonConvert.DeserializeObject<JArray>(lxrStr);
                                    if (lxrArray != null && lxrArray.Count > 0)
                                    {
                                        var lxrList = lxrArray.Select(x =>
                                        {
                                            string gender = x["gender"].ToStringV1().EqualsV1("1") ? "SEX01_SYS" : "SEX02_SYS";
                                            string name = x["name"].ToStringV1();
                                            string email = x["email"].ToStringV1();
                                            string post = x["post"].ToStringV1();
                                            string tel = string.Empty;
                                            JArray telArray = JsonConvert.DeserializeObject<JArray>(x["tel_list"].ToStringV1());
                                            if (telArray != null && telArray.Count > 0)
                                                tel = telArray.FirstOrDefault().ToStringV1();
                                            string address = "address".GetValueByKey(xmdatas);
                                            return new
                                            {
                                                gender = gender,
                                                name = name,
                                                email = email,
                                                post = post,
                                                tel = tel,
                                                address = address,
                                            };
                                        }).ToList();
                                        if (lxrList.Count > 0)
                                        {
                                            JObject Root = new JObject();
                                            JArray ModelArray = new JArray();
                                            foreach (var lxr in lxrList)
                                            {
                                                JObject Model = new JObject();
                                                Model["FCONTACTID"] = 0;
                                                Model["FName"] = lxr.name;
                                                Model["FCompanyType"] = "BD_Customer";

                                                JObject FCompany = new JObject();
                                                FCompany["FNumber"] = custNo;
                                                Model["FCompany"] = FCompany;

                                                JObject Fex = new JObject();
                                                Fex["FNumber"] = lxr.gender;
                                                Model["Fex"] = Fex;

                                                Model["FPost"] = lxr.post;
                                                Model["FMobile"] = lxr.tel;
                                                Model["FBizLocNumber"] = lxr.tel;
                                                Model["FBizLocation"] = lxr.address;
                                                Model["FEmail"] = lxr.email;

                                                ModelArray.Add(Model);
                                            }
                                            Root["Model"] = ModelArray;
                                            json = Root.ToStringV1();
                                            msg = string.Empty;
                                            returnData = new JObject();
                                            isok = K3HelperV1.BatchSave(ctx, "BD_CommonContact", json, ref msg, ref returnData);
                                            LogHelper.XiaoManLog($"【联系人保存结果：{isok.ToStringV1()}】【客户名称：{uObj.Name}】\n【返回结果:{returnData.ToStringV1()}】\n【json:{json}】", logType);
                                            if (isok)
                                            {
                                                suStr = returnData["Result"]["ResponseStatus"]["SuccessEntitys"].ToStringV1();
                                                array = JsonConvert.DeserializeObject<JArray>(suStr);
                                                List<string> lxrNos = array.Select(x => x["Number"].ToStringV1()).Where(x => !x.IsNullOrEmptyOrWhiteSpace()).ToList();
                                                if (lxrNos.Count > 0)
                                                {
                                                    Root = new JObject();
                                                    JObject Model = new JObject();
                                                    Model["FID"] = custId;
                                                    JArray xlrArray = new JArray();
                                                    foreach (var xlrNo in lxrNos)
                                                    {
                                                        JObject xlrObj = new JObject();

                                                        JObject FContactId = new JObject();
                                                        FContactId["FNumber"] = xlrNo;
                                                        xlrObj["FContactId"] = FContactId;

                                                        xlrObj["FIsDefaultConsigneeCT"] = false;
                                                        xlrObj["FIsCopy"] = false;
                                                        xlrArray.Add(xlrObj);
                                                    }
                                                    Model["FT_BD_CUSTLOCATION"] = xlrArray;
                                                    Root["Model"] = Model;
                                                    json = Root.ToStringV1();
                                                    msg = string.Empty;
                                                    isok = K3HelperV1.Save(ctx, formId, json, ref msg);
                                                    if (!isok)
                                                        isok = K3HelperV1.Draft(ctx, formId, json, ref msg);
                                                    if (isok)
                                                        LogHelper.XiaoManLog($"【客户保存联系人成功】【客户名称：{uObj.Name}】\n【json:{json}】", logType);
                                                    else
                                                        LogHelper.XiaoManLog($"【客户保存联系人失败】【客户名称：{uObj.Name}】\n【msg:{msg}】\n【json:{json}】", logType);
                                                }
                                            }

                                        }


                                    }


                                }
                            }
                            else
                            {
                                LogHelper.XiaoManLog($"【客户保存失败】【{uObj.Name}】\n【msg:{msg}】\n【json:{json}】", logType);
                                continue;
                            }
                            string sql_del = $@"/*dialect*/ select distinct FCUSTID from T_BD_CUSTOMER where FDOCUMENTSTATUS='Z' and ISNULL(FNUMBER,'')='' and ISNULL(F_RLKX_xmcustid1,'')=''";
                            DynamicObjectCollection delDatas = DBUtils.ExecuteDynamicObject(ctx,sql_del);
                            if (delDatas!=null&&delDatas.Count>0)
                            {
                                List<int> cids = delDatas.Select(x => x["FCUSTID"].ToStringV1().ToInt32V1()).ToList();
                                JObject DelRoot = new JObject();
                                DelRoot["Ids"] = string.Join(",",cids);
                                string delJson = DelRoot.ToStringV1();
                                string delmsg = string.Empty;
                                bool delStatus=  K3HelperV1.Delete(ctx,formId,delJson,ref delmsg);
                            }
                        }

                    }
                }
                catch (Exception ex)
                {
                    LogHelper.XiaoManLog($"【获取客户详细信息】【异常CDetail2002】\n【msg:{ex.Message}】", logType);
                    continue;
                }


            }
        }


        public string FillContent(JObject dataObj, CustUpdateData uObj, List<XMFieldData> xmdatas)
        {
            JArray companyArray = JsonConvert.DeserializeObject<JArray>(dataObj["company"].ToStringV1());

            JObject Root = new JObject();
            JObject Model = new JObject();
            Model["FID"] = 0;
            Model["FIsTrade"] = true;
            //小满客户Id
            Model["F_RLKX_xmcustid1"] = uObj.Id;
            //客户编号
            Model["FNumber "] = uObj.SerId;
            //客户名称
            Model["FName"] = uObj.Name;
            //客户简称
            Model["FShortName"] = uObj.ShortName;
            //创建组织
            JObject FCreateOrgId = new JObject();
            FCreateOrgId["FNumber"] = "100";
            Model["FCreateOrgId"] = FCreateOrgId;
            //使用组织
            JObject FUseOrgId = new JObject();
            FUseOrgId["FNumber"] = "100";
            Model["FUseOrgId"] = FUseOrgId;
            //结算币别
            {
                string jsbb = "35245757951184".GetValueByKey(xmdatas);
                var jsbbObj = currencyList.Where(x => x.Name.EqualsV1(jsbb)).FirstOrDefault();
                JObject FTRADINGCURRID = new JObject();
                FTRADINGCURRID["FNumber"] = jsbbObj==null?"": jsbbObj.Number.ToStringV1();
                Model["FTRADINGCURRID"] = FTRADINGCURRID;
            }
            //收款条件
            {
                string sktj = "35246794970711".GetValueByKey(xmdatas);
                var sktjObj = receiptConditionList.Where(x => x.Name.EqualsV1(sktj)).FirstOrDefault();
                JObject FRECCONDITIONID = new JObject();
                FRECCONDITIONID["FNumber"] = sktjObj==null?"": sktjObj.Number.ToStringV1();
                Model["FRECCONDITIONID"] = FRECCONDITIONID;
            }
            //结算方式
            {
                string jsfs = "35247614741502".GetValueByKey(xmdatas);
                var jsfsObj = settleTypeList.Where(x => x.Name.EqualsV1(jsfs)).FirstOrDefault();
                JObject FSETTLETYPEID = new JObject();
                FSETTLETYPEID["FNumber"] = jsfsObj==null?"": jsfsObj.Number.ToStringV1();
                Model["FSETTLETYPEID"] = FSETTLETYPEID;
            }
            //价格条款
            {
                string gjtk = "35249005854386".GetValueByKey(xmdatas);
                var gjtkObj = priceClauseList.Where(x => x.Name.EqualsV1(gjtk)).FirstOrDefault();
                JObject F_RLKX_jgtk = new JObject();
                F_RLKX_jgtk["FNumber"] = gjtkObj==null?"": gjtkObj.Number.ToStringV1();
                Model["F_RLKX_jgtk"] = F_RLKX_jgtk;
            }
           

            //对账收件邮箱
            {
                string xiaomanValue = "35249113459539".GetValueByKey(xmdatas);
                Model["F_RLKX_dzemail"] = xiaomanValue;
            }
            //发票抬头
            {
                string xiaomanValue = "35249210606679".GetValueByKey(xmdatas);
                Model["FINVOICETITLE"] = xiaomanValue;
            }
            //纳税登记号
            {
                string xiaomanValue = "35249210606679".GetValueByKey(xmdatas);
                Model["FINVOICETITLE"] = xiaomanValue;
            }
            //开户银行
            {
                string xiaomanValue = "35249254357822".GetValueByKey(xmdatas);
                Model["FINVOICEBANKNAME"] = xiaomanValue;
            }
            //银行账号
            {
                string xiaomanValue = "35249277712401".GetValueByKey(xmdatas);
                Model["FINVOICEBANKACCOUNT"] = xiaomanValue;
            }
            //开票联系电话
            {
                string xiaomanValue = "35249293201414".GetValueByKey(xmdatas);
                Model["FINVOICETEL"] = xiaomanValue;
            }
            //开票通讯地址
            {
                string xiaomanValue = "35249310290788".GetValueByKey(xmdatas);
                Model["FINVOICEADDRESS"] = xiaomanValue;
            }
            //统一社会信用代码
            {
                string xiaomanValue = "35249333470956".GetValueByKey(xmdatas);
                Model["FSOCIALCRECODE"] = xiaomanValue;
            }
            //收票邮箱
            {
                string xiaomanValue = "35249113459539".GetValueByKey(xmdatas);
                Model["F_RLKX_email"] = xiaomanValue;
            }
            //客户分组
            {
                string xiaomanValue = "35249412150502".GetValueByKey(xmdatas);
                var custObj = custGroupList.Where(x => x.Name.EqualsV1(xiaomanValue)).FirstOrDefault();
                JObject FGroup = new JObject();
                FGroup["FNumber"] = custObj==null?"": custObj.Number.ToStringV1();
                Model["FGroup"] = FGroup;
            }
            //主营业务
            {
                string xiaomanValue = "35249438173304".GetValueByKey(xmdatas);
                Model["FDescription"] = xiaomanValue;
            }
            //业务员客户类别
            {
                string xiaomanValue = "35249540874681".GetValueByKey(xmdatas);
                var k3Value = MJList.Where(x => x.TypeName.EqualsV1("业务员客户类别") && x.Name.EqualsV1(xiaomanValue)).FirstOrDefault();
                Model["F_RLKX_YWYKHLB"] = k3Value==null?"": k3Value.Number.ToStringV1();

            }
            //默认税率
            {
                string xiaomanValue = "35249746646548".GetValueByKey(xmdatas);
                var k3Value = taxRateList.Where(x => x.Name.EqualsV1(xiaomanValue)).FirstOrDefault();
                JObject FTaxRate = new JObject();
                FTaxRate["FNumber"] = k3Value==null?"": k3Value.Number.ToStringV1();
                Model["FTaxRate"] = FTaxRate;
            }

            //州
            JObject F_RLKX_continent = new JObject();
            F_RLKX_continent["FNumber"] = "";
            Model["F_RLKX_continent"] = F_RLKX_continent;

            //国家
            {
                string country = "country".GetValueByKey(xmdatas);
                if (!country.IsNullOrEmptyOrWhiteSpace())
                {
                    var countryNumber = auxiliaryList.Where(x => x.TypeName.EqualsV1("国家") && x.Name.EqualsV1(country)).FirstOrDefault();
                    JObject FCOUNTRY = new JObject();
                    FCOUNTRY["FNumber"] = countryNumber==null?"": countryNumber.Number.ToStringV1();
                    Model["FCOUNTRY"] = FCOUNTRY;
                }
            }

            //地区
            JObject FPROVINCIAL = new JObject();
            FPROVINCIAL["FNumber"] = "";
            Model["FPROVINCIAL"] = FPROVINCIAL;
            //地址
            string address = "address".GetValueByKey(xmdatas);
            Model["FADDRESS"] = address;
            //销售员
            //string saler = "28514799207966".GetValueByKey(xmdatas);
            string saler = string.Empty;
            JArray salerArray = JsonConvert.DeserializeObject<JArray>(dataObj["owner"].ToStringV1());
            if (salerArray!=null&& salerArray.Count>0)
            {
                JObject salerObj = salerArray[0] as JObject;
                saler = salerObj["name"].ToStringV1();
            }
            if (!saler.IsNullOrEmptyOrWhiteSpace())
            {
                var salerObj = salerList.Where(x => x.Name.EqualsV1(saler)).FirstOrDefault();
                if (salerObj != null)
                {
                    //部门
                    JObject FSALDEPTID = new JObject();
                    FSALDEPTID["FNumber"] = salerObj.dptNumebr.ToStringV1();
                    Model["FSALDEPTID"] = FSALDEPTID;
                    //销售员
                    JObject FSELLER = new JObject();
                    FSELLER["FNumber"] = salerObj.Number.ToStringV1();
                    Model["FSELLER"] = FSELLER;
                }
            }
            Model["FISCREDITCHECK"] = true;

            //客户类别
            {
                string custType = "32483931076905".GetValueByKey(xmdatas);
                var custTypeNumber = auxiliaryList.Where(x => x.TypeName.EqualsV1("客户类别") && x.Name.EqualsV1(custType)).FirstOrDefault();
                JObject FCustTypeId = new JObject();
                FCustTypeId["FNumber"] = custTypeNumber==null?"": custTypeNumber.Number.ToStringV1();
                Model["FCustTypeId"] = FCustTypeId;
            }

            //客户等级
            {
                string custGrade = "26057260649788".GetValueByKey(xmdatas);
                var custGradeNumber = custGradeList.Where(x => x.Name.EqualsV1(custGrade)).FirstOrDefault();
                JObject F_RLKX_khdj = new JObject();
                F_RLKX_khdj["FNumber"] = custGradeNumber==null?"": custGradeNumber.Number.ToStringV1();
                Model["F_RLKX_khdj"] = F_RLKX_khdj;
            }


            //公司规模
            {
                string companyScale = "32485585051114".GetValueByKey(xmdatas);
                var companyScaleNumber = auxiliaryList.Where(x => x.TypeName.EqualsV1("公司规模") && x.Name.EqualsV1(companyScale)).FirstOrDefault();
                JObject FCompanyScale = new JObject();
                FCompanyScale["FNumber"] = companyScaleNumber==null?"": companyScaleNumber.Number.ToStringV1();
                Model["FCompanyScale"] = FCompanyScale;
            }

            //公司类别
            {
                string companyClassify = "32484180567865".GetValueByKey(xmdatas);
                var companyClassifyNumber = auxiliaryList.Where(x => x.TypeName.EqualsV1("公司类别") && x.Name.EqualsV1(companyClassify)).FirstOrDefault();
                JObject FCompanyClassify = new JObject();
                FCompanyClassify["FNumber"] = companyClassifyNumber==null?"": companyClassifyNumber.Number.ToStringV1();
                Model["FCompanyClassify"] = FCompanyClassify;
            }

            //公司性质
            {
                string companyNature = "32485517064215".GetValueByKey(xmdatas);
                var companyNatureNumber = auxiliaryList.Where(x => x.TypeName.EqualsV1("公司性质") && x.Name.EqualsV1(companyNature)).FirstOrDefault();
                JObject FCompanyNature = new JObject();
                FCompanyNature["FNumber"] = companyNatureNumber==null?"": companyNatureNumber.Number.ToStringV1();
                Model["FCompanyNature"] = FCompanyNature;
            }
            //客户行业
            {
                string KHHY = "32485651749168".GetValueByKey(xmdatas);
                var KHHYNumber = auxiliaryList.Where(x => x.TypeName.EqualsV1("客户行业") && x.Name.EqualsV1(KHHY)).FirstOrDefault();
                JObject F_RLKX_KHHY = new JObject();
                F_RLKX_KHHY["FNumber"] = KHHYNumber==null?"": KHHYNumber.Number.ToStringV1();
                Model["F_RLKX_KHHY"] = F_RLKX_KHHY;
            }



            //客户来源
            {
                string KHLY = "origin".GetValueByKey(xmdatas);
                var KHLYNumber = custSourceList.Where(x => x.Name.EqualsV1(KHLY)).FirstOrDefault();
                JObject F_RLKX_KHLY = new JObject();
                F_RLKX_KHLY["FNumber"] = KHLYNumber==null?"": KHLYNumber.Number.ToStringV1();
                Model["F_RLKX_KHLY"] = F_RLKX_KHLY;
            }
            //成交状态
            string cjzt = "34856303195581".GetValueByKey(xmdatas);
            string cjztValue = cjzt.EqualsV1("已成交") ? "B" : "A";
            Model["F_RLKX_cjzt"] = cjztValue;

            //处理商户信息 (子单据头)
            {
                JObject swxx = new JObject();
                swxx["FEntryId"] = 0;
                //省份 
                string province = "province".GetValueByKey(xmdatas);
                var provinceNumber = auxiliaryList.Where(x => x.TypeName.EqualsV1("省份") && x.Name.EqualsV1(province)).FirstOrDefault();
                JObject FPROVINCE = new JObject();
                FPROVINCE["FNumber"] = provinceNumber==null?"": provinceNumber.Number.ToStringV1();
                swxx["FPROVINCE"] = FPROVINCE;
                //城市 
                string city = "city".GetValueByKey(xmdatas);
                var cityNumber = auxiliaryList.Where(x => x.TypeName.EqualsV1("市") && x.Name.EqualsV1(city)).FirstOrDefault();
                JObject FCITY = new JObject();
                FCITY["FNumber"] = cityNumber==null?"": cityNumber.Number.ToStringV1();
                swxx["FCITY"] = FCITY;

                Model["FT_BD_CUSTOMEREXT"] = swxx;
            }

            Root["Model"] = Model;
            string json = Root.ToStringV1();
            return json;
        }

    }
}
